import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:ivy_baby_record/user/api/login_util.dart';
import 'package:ivy_baby_record/user/colors/colors.dart';
import 'package:ivy_baby_record/user/pages/base/base_edittext.dart';
import 'package:ivy_baby_record/user/pages/base/init_reg_base.dart';
import 'package:ivy_baby_record/user/pages/login/reg_login_notifier.dart';
import 'package:ivy_baby_record/user/util/countdown.dart';
import 'package:ivy_baby_record/user/util/ui_util.dart';
import 'package:ivybaby_api/api/base/api_base.dart';
import 'package:ivy_baby_record/ivy_baby_record.dart';
import 'package:ivy_baby_record/user/api/verify/verify.impl.dart';
import 'package:provider/provider.dart';

class RegLoginPage extends InitRegLoginPage {
  final bool isReg;

  RegLoginPage(params) :
        this.isReg = params['isReg'],
        super(params: params);

  @override
  State<StatefulWidget> createState() => _RegLoginPageState();
}

class _RegLoginPageState extends InitRegLoginPageState<RegLoginPage> {
  late RegLoginNotifier regLoginNotifier;
  late CountDown countDown;

  @override
  bool get showTitle => false;

  @override
  void initState() {
    regLoginNotifier = RegLoginNotifier();
    super.initState();

    regLoginNotifier.isReg = widget.isReg;
  }

  @override
  void dispose() {
    super.dispose();
    countDown?.dispose();
    regLoginNotifier?.dispose();
  }

  void close() {
    releaseTextures();
    List<String> urls = [];
    urls.add('actionbar_back_press');
    urls.add('share_weixin_white');
    urls.add('share_qq_white');
    urls.add('share_weibo_white');
    urls.add('alipay_login_icon');
    urls.add('share_huawei_white');
    urls.add('audio_tab_normal_night');
    IvyBabyRecord.releaseList(urls);
    if (Navigator.of(context).canPop()) {
      Navigator.of(context).pop();
    } else {
      SystemNavigator.pop(animated: true);
    }
  }

  @override
  bool onKeyCodeBackClick(BuildContext context) {
    if (regLoginNotifier.isUsePswLogin) {
      regLoginNotifier.updateIsUsePswLogin(false);
    } else if (regLoginNotifier.isReg) {
      if (!widget.isReg) {
        regLoginNotifier.updateIsReg(false);
      } else {
        close();
        return true;
      }
    } else {
      if (widget.isReg) {
        regLoginNotifier.updateIsReg(true);
      } else {
        close();
        return true;
      }
    }

    return false;
  }

  @override
  Widget buildDetailContent(BuildContext context) {
    return Container(
      child: ChangeNotifierProvider(
        create: (context) => regLoginNotifier,
        child: Consumer<RegLoginNotifier>(
          builder: (context, notifier, child) {
            return Stack(
              alignment: Alignment.topCenter,
              children: [
                Positioned(
                    left: 20,
                    top: 30,
                    width: 32,
                    height: 32,
                    child: GestureDetector(
                      onTap: () {
                        onKeyCodeBackClick(context);
                      },
                      child: UIUtils.getWidgetByTextureId(notifier.backId),
                    )
                ),

                Positioned(
                  left: 40,
                  top: 85,
                  right: 40,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                          notifier.isUsePswLogin ? '密码登录' : (notifier.isReg ? '为保障宝宝信息安全，请绑定手机号' : '欢迎'),
                          style: TextStyle(
                              fontSize: notifier.isReg ? 18 : 32, color: notifier.isReg ? Colors.white60 : Colors.white
                          )
                      ),

                      SizedBox(height: 28),

                      Container(
                        height: ScreenUtil().setWidth(48),
                        child: Row(
                          children: [
                            Container(
                              height: ScreenUtil().setWidth(48),
                              child: Stack(
                                children: [
                                  Column(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Row(
                                        crossAxisAlignment: CrossAxisAlignment.center,
                                        children: [
                                          Text(notifier.dialCode, style: TextStyle(fontSize: 18, color: Colors.white)),
                                          Container(
                                            width: 8,
                                            height: 5,
                                            child: UIUtils.getWidgetByTextureId(notifier.downIndId),
                                          )
                                        ],
                                      ),
                                    ],
                                  ),
                                  Positioned(child: Container(
                                    width: 48,
                                    child: Divider(height: 1, color: Colors.white),
                                  ), bottom: 0,)
                                ],
                              ),
                            ),

                            SizedBox(width: 5),

                            Expanded(child: Container(
                              child: EditText('手机号', notifier.mobile, (value) {
                                notifier.updateMobile(value);
                              }, TextInputType.phone, 16),
                            ), flex: 6),
                          ],
                        ),
                      ),

                      Container(
                        height: ScreenUtil().setWidth(48),
                        child: Stack(
                          children: [
                            EditText(notifier.isUsePswLogin ? '密码' : '短信验证码', notifier.code, (value) {
                              notifier.updateCode(value);
                            }, TextInputType.number, 16, maxLength: notifier.isUsePswLogin ? 16 : 4),
                            Positioned(
                                right: 0,
                                child: Offstage(
                                  offstage: notifier.isUsePswLogin,
                                  child: TextButton(
                                    style: TextButton.styleFrom(
                                      minimumSize: Size(100, 80),
                                      backgroundColor: Colors.white,
                                      shape: RoundedRectangleBorder(
                                          side: BorderSide.none,
                                          borderRadius: BorderRadius.all(Radius.circular(6))
                                      ),
                                      textStyle: TextStyle(
                                        color: CustomColors.c8,
                                      )
                                    ),
                                    // minWidth: 100,
                                    // height: 30,
                                    // color: Colors.white,
                                    // textColor: CustomColors.c8,
                                    onPressed: () {
                                      if (notifier.mobile.isEmpty) {
                                        return;
                                      }

                                      if (!notifier.isCountdown) {
                                        notifier.isCountdown = true;
                                        ApiUtils.inst.sendSMSVerifyCode(notifier.mobile, type: notifier.isReg ? 'register' : 'login').then((value) {
                                          if (value.isSuccess) {
                                            /// 倒计时
                                            countDown = CountDown.fromNow(value.data!.leftLimitSecond, (leftSeconds, {days, hours, minutes, seconds}) {
                                              notifier.updateCountdown('$leftSeconds秒');
                                              if (leftSeconds == 0) {
                                                notifier.updateIsCountdown(false);
                                              }
                                            });
                                            countDown.startCountDown();
                                          }
                                        });
                                      }
                                    },
                                    child: Text(notifier.isCountdown ? notifier.countdown : '获取验证码', style: TextStyle(fontSize: 14, color: CustomColors.c8)),
                                    // shape: RoundedRectangleBorder(
                                    //     side: BorderSide.none,
                                    //     borderRadius: BorderRadius.all(Radius.circular(6))
                                    // ),
                                  ),
                                )
                            ),
                          ],
                        ),
                      ),

                      Container(
                        margin: EdgeInsets.symmetric(vertical: 20),
                        child: Row(
                          children: [
                            Expanded(child: TextButton(
                              style: TextButton.styleFrom(
                                backgroundColor: Colors.white,
                                minimumSize: Size(120, 48),
                                textStyle: TextStyle(
                                  color: CustomColors.c8,
                                ),
                                shape: RoundedRectangleBorder(
                                    side: BorderSide.none,
                                    borderRadius: BorderRadius.all(Radius.circular(100))
                                ),
                                disabledBackgroundColor: Colors.white70,
                              ),
                              // height: 48,
                              // color: Colors.white,
                              // textColor: CustomColors.c8,
                              // disabledColor: Colors.white70,
                              onPressed: !isRegOrLoginEnabled() ? null : () {
                                if (notifier.isReg) {
                                  ApiUtils.inst.fastRegisterByMobile(notifier.mobile, notifier.code).then((value) {
                                    LoginUtil.loginResultProcess(context, value);
                                  });
                                } else {
                                  ApiUtils.inst.loginByMobile(notifier.mobile, notifier.code).then((value) {
                                    LoginUtil.loginResultProcess(context, value);
                                  });
                                }
                              },
                              child: Text(notifier.isReg ? '完成' : '登录', style: TextStyle(fontSize: 20, color: CustomColors.c8, fontWeight: FontWeight.bold)),
                              // shape: RoundedRectangleBorder(
                              //     side: BorderSide.none,
                              //     borderRadius: BorderRadius.all(Radius.circular(100))
                              // ),
                            ))
                          ],
                        ),
                      ),

                      Offstage(
                        offstage: notifier.isReg && !notifier.isUsePswLogin,
                        child: GestureDetector(
                          onTap: () {
                            if (notifier.isUsePswLogin) {
                              /// TODO ： 找回密码
                              return;
                            }
                            notifier.updateIsUsePswLogin(true);
                          },
                          child: Center(
                            child: Text(notifier.isUsePswLogin ? '密码忘记？点此找回' : '使用密码登录', style: TextStyle(fontSize: 14, color: Colors.white)),
                          ),
                        ),
                      ),

                      Offstage(
                        offstage: !notifier.isReg || notifier.isUsePswLogin,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Container(
                              width: 12,
                              height: 12,
                              margin: EdgeInsets.only(right: 2),
                              child: GestureDetector(
                                onTap: () {
                                  notifier.updateIsAgree(!notifier.agreement);
                                },
                                child: UIUtils.getWidgetByTextureId(notifier.agreement ? checkTextureId : uncheckTextureId),
                              ),
                            ),

                            RichText(
                              text: TextSpan(
                                  style: TextStyle(fontSize: 14, color: Colors.white),
                                  children: [
                                    TextSpan(text: '已阅读并同意 '),
                                    TextSpan(
                                        text: '使用条款与隐私政策',
                                        style: TextStyle(fontSize: 14, color: Colors.white, decoration: TextDecoration.underline),
                                        recognizer: TapGestureRecognizer()
                                          ..onTap = () {
                                            /// TODO : 跳转使用条款与隐私政策
                                            /// Navigator.of(context).pushNamed('login');
                                          }
                                    ),
                                  ]
                              ),
                            )
                          ],
                        ),
                      ),

                      SizedBox(height: 30),

                      Offstage(
                        offstage: notifier.isReg || notifier.isUsePswLogin,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            GestureDetector(
                                onTap: () {

                                },
                                child: Container(
                                  width: 48,
                                  height: 48,
                                  child: UIUtils.getWidgetByTextureId(notifier.wxId),
                                )
                            ),
                            GestureDetector(
                                onTap: () {

                                },
                                child: Container(
                                  width: 48,
                                  height: 48,
                                  child: UIUtils.getWidgetByTextureId(notifier.qqId),
                                )
                            ),
                            GestureDetector(
                                onTap: () {

                                },
                                child: Container(
                                  width: 48,
                                  height: 48,
                                  child: UIUtils.getWidgetByTextureId(notifier.weiBoId),
                                )
                            ),
                            GestureDetector(
                                onTap: () {

                                },
                                child: Container(
                                  width: 48,
                                  height: 48,
                                  child: UIUtils.getWidgetByTextureId(notifier.aliId),
                                )
                            ),
                          ],
                        ),
                      )
                    ],
                  ),
                ),

                Positioned(
                  bottom: ScreenUtil().setWidth(20),
                  child: Offstage(
                    offstage: notifier.isUsePswLogin,
                    child: RichText(
                      text: TextSpan(
                          style: TextStyle(fontSize: 16, color: Colors.white),
                          children: [
                            TextSpan(text: notifier.isReg ? '已有账号，点此' : '没有有账号，快速'),
                            TextSpan(
                                text: notifier.isReg ? '登录' : '注册',
                                style: TextStyle(fontSize: 16, color: Colors.white, decoration: TextDecoration.underline),
                                recognizer: TapGestureRecognizer()
                                  ..onTap = () {
                                  notifier.updateIsReg(!notifier.isReg);
                                }
                            ),
                          ]
                      ),
                    ),
                  ),
                ),
              ],
            );
          },
        ),
      ),
    );
  }

  bool isRegOrLoginEnabled() {
    bool isInvalidData = regLoginNotifier.mobile.isEmpty || regLoginNotifier.code.isEmpty
        || regLoginNotifier.mobile.length < 11 || regLoginNotifier.code.length < 4;
    if (regLoginNotifier.isReg) {
      return regLoginNotifier.agreement && !isInvalidData;
    }
    return !isInvalidData;
  }

  @override
  Future<void> loadBackgroundImageWithTexture() async {
    super.loadBackgroundImageWithTexture();
    int backId = -1;
    int wxId = -1;
    int qqId = -1;
    int weiBoId = -1;
    int aliId = -1;
    int hwId = -1;
    int downIndId = -1;
    try {
      backId = await IvyBabyRecord.loadImage('actionbar_back_press');
      wxId = await IvyBabyRecord.loadImage('share_weixin_white');
      qqId = await IvyBabyRecord.loadImage('share_qq_white');
      weiBoId = await IvyBabyRecord.loadImage('share_weibo_white');
      aliId = await IvyBabyRecord.loadImage('alipay_login_icon');
      hwId = await IvyBabyRecord.loadImage('share_huawei_white');
      downIndId = await IvyBabyRecord.loadImage('audio_tab_normal_night');
    } on PlatformException {
      print('loadImage exception!');
    }

    if (!mounted) return;

    regLoginNotifier.updateTextureIds(backId, wxId, qqId, weiBoId, aliId, hwId, downIndId);
  }
}